const fs = require("fs");
const path = require("path");

const m3u8ToMp4 = require("./index.js"); // 引入核心模块，注意路径
const converter = new m3u8ToMp4();
const {setFileName} = require('../../utils/files.js')
let animeInde = 0 

function downloadMovie(opt, callback) {
    // 测试视频，如果链接失效的话就自己找一个
    let url = opt.url || "https://9.thehanju.com/file/taiju01/pics/2023/6/19/uQINGJ93/playlista.m3u8";
    let output = opt.output || 'movie';
    let filename =`${opt.name}.mp4`;
    let title = opt.title || '测试视频';

    if (!fs.existsSync(output)) {
        fs.mkdirSync(output, {
            recursive: true,
        });
    }

    (async function () {
        console.log("准备下载...");
        
        await converter
        .setInputFile(url)
        .setOutputFile(path.join(output, filename))
        .start();
        
        console.log("下载完成!");
        
        if (typeof callback === 'function') callback();
        try {
        } catch (error) {
            throw new Error("哎呀，出错啦! 检查一下参数传对了没喔。", error);
        }
    })();

}


function doenloadSeries(opt,callback){
    // 测试视频，如果链接失效的话就自己找一个
    let url = opt.url
    let output = `anime/${opt.name}`;
    let filename = `${opt.name}${setFileName(animeInde + 1, String(url.length).length)}.mp4`;
    let title = opt.title || '测试视频';

    if (!fs.existsSync(output)) {
        fs.mkdirSync(output, {
            recursive: true,
        });
    }

    (async function () {
        console.log("准备下载...");

        await converter
            .setInputFile(url[animeInde])
            .setOutputFile(path.join(output, filename))
            .start();

        console.log(`${filename}下载完成!`);
        animeInde += 1

        if (animeInde < url.length){
            doenloadSeries(opt)
        }

        if (typeof callback === 'function') callback();
        try {
        } catch (error) {
            throw new Error("哎呀，出错啦! 检查一下参数传对了没喔。", error);
        }
    })();
}


module.exports ={
    downloadMovie,
    doenloadSeries
}

